package au.com.langdale.gwt.client.ui;

import au.com.langdale.gwt.client.model.ModelListener;
import au.com.langdale.gwt.client.remote.EditManager;
import au.com.langdale.gwt.client.remote.RemoteList;

import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * A user interface to control an EditManager. Buttons are
 * provided to save changes, reset (discard) changes, 
 * or delete the selected row.  The reset button is available
 * if a RemoteList is provided.
 *  
 * @author adv
 *
 */
public class EditBar extends Composite implements ModelListener {
	private EditManager manager;
	private RemoteList source;
	private final HorizontalPanel horizontalPanel = new HorizontalPanel();
	private final Button saveButton = new Button();
	private final Button deleteButton = new Button();
	private final Button resetButton = new Button();
	
	public EditBar() {
		initWidget(horizontalPanel);

		horizontalPanel.add(deleteButton);
		deleteButton.setText("Delete");
		deleteButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				manager.delete();
			}
		});

		horizontalPanel.add(resetButton);
		resetButton.setText("Reset");
		resetButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				if( source != null)
					source.refresh();
			}
		});

		horizontalPanel.add(saveButton);
		saveButton.setText("Save");
		saveButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				manager.save();
			}
		});
	}
	
	public EditManager getManager() {
		return manager;
	}

	public void setManager(EditManager editManager) {
		if( manager != null)
			manager.removeModelListener(this);
		manager = editManager;
		manager.addModelListener(this);
		onChange(manager);
	}

	public void onChange(Object sender) {
		saveButton.setEnabled(manager.hasUpdates());
		deleteButton.setEnabled(manager.canDelete());
		resetButton.setEnabled(source != null && manager.hasUpdates());
	}

	public void onCommit(Object container) {
		// does not affect us		
	}

	public void onContentsChange(Object container) {
		// does not affect us
	}

	public void onModelChange(Object model) {
		// does not affect us		
	}

	public RemoteList getSource() {
		return source;
	}

	public void setSource(RemoteList source) {
		this.source = source;
		if( manager != null)
			onChange(manager);
	}
}
